package archivemanagement;

import static com.google.common.base.Throwables.propagate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import libraries.Library;

import com.google.inject.Inject;

public class LibraryManager implements ArchiveManager<String, Library> {
    
    private final ArrayList<LibraryArchive> libraries;
    
    @Inject
    private LibraryManager(LibraryArchive... operatorLibraries)
    {
        libraries = new ArrayList<LibraryArchive>(Arrays.asList(operatorLibraries));
    }
    
    @Override
    public Library load(String key)
    {
        for(LibraryArchive lib : libraries) {
            Library library;
            try {
                library = lib.loadLibrary(key);
                if(library != null) {
                    return library;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return null;
    }
    
    @Override
    public void add(Library value)
    {
        for(LibraryArchive lib : libraries) {
            try {
                lib.writeLibrary(value);
            }
            catch(IOException e) {
                propagate(e);
            }
        }
    }
    
    @Override
    public int update(Library value)
    {
        int updatedLibraries = 0;
        for(LibraryArchive lib : libraries) {
            try {
                if(lib.containsLibrary(value.getName())) {
                    lib.writeLibrary(value);
                    updatedLibraries++;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return updatedLibraries;
    }
    
    @Override
    public Collection<Library> loadAll()
    {
        ArrayList<Library> Libraries = new ArrayList<Library>();
        for(LibraryArchive lib : libraries) {
            try {
                Libraries.addAll(lib.loadAllLibraries());
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return Libraries;
    }
}